#include "stm32f10x.h"
#include "delay.h"
#include "ESP8266.h"
#include "pwm.h"
#include "usart.h"

#define USART USART1

char data[20]="\0\0"; int dataLen=0;

//u8 ESP8266_SendData(char* dat){
//	int len=0;
//	for (len=0;dat[len]!='\0';len++){
//		USART_SendData(USART1,(int)dat[len]);
//		USART_SendData(USART2,(int)dat[len]);
//		while(!USART_GetFlagStatus(USART1,USART_FLAG_TC));
//	}
//	USART_SendData(USART1,0x0D);
//	while(!USART_GetFlagStatus(USART1,USART_FLAG_TC));
//	USART_SendData(USART1,0x0A);
//	while(!USART_GetFlagStatus(USART1,USART_FLAG_TC));
//	
//	return 1;
//}

void ESP8266_Init(void){
	char cmd[2]={0x0D,0x0A};
	USART_Send(USART," AT",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+RST",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+CWMODE=2",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+CWSAP=\"ESP8266_TEST\",\"1234567890\",1,3",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+CIPMUX=1",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+CIPSERVER=1,8080",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
}

void ESP8266_Init2(void){
	char cmd[2]={0x0D,0x0A};
	
	USART_Send(USART," AT",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+RST",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+CWMODE=1",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+CWJAP=\"西天取经\",\"xtqj0115\"",0);
	//USART_Send(USART," AT+CWJAP=\"nova 7 SE 5G\",\"1213121311\"",0);
	
	USART_Send(USART,cmd,2);
	delay_ms(10000);
	USART_Send(USART," AT+CIPMUX=1",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+CIPSERVER=1,8080",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
	USART_Send(USART," AT+CIFSR",0);
	USART_Send(USART,cmd,2);
	delay_ms(500);
}

#include <math.h>

void CIPSEND(char* dat,int door){
	int len=0; int len2=0; int i=0;
	char cmd[]=" AT+CIPSEND=0,1";
	cmd[12]=(char)(door+48);
	for(;dat[len]!='\0';len++);
	for(;pow(10,len2)<len||pow(10,len2)==len;len2++);
	cmd[14+len2]=0x0D; cmd[15+len2]=0x0A; cmd[16+len2]='\0';
	dat[len]=0x0D; dat[len+1]=0x0A; dat[len+2]='\0';
	for(;i<len2;i++){
		cmd[14+i]=(char)(48+len/(int)(pow(10,len2-1-i)));
		len%=(int)(pow(10,len2-i-1));
	}
	USART_Send(USART,cmd,0);
	delay_ms(500);
	USART_Send(USART,dat,0);
}

void ESP_GetData(u8 dat){
	if ((char)dat=='o'){
		int arr=0;
		arr+=(int)(data[dataLen-1]-48);
		delay_ms(100);
		CIPSEND(data,0);
		data[0]='\0';
		data[1]='\0';	
		dataLen=0;		
	}else{
		data[dataLen]=(char)dat;
		dataLen++;
		data[dataLen]='\0';
	}
}
